﻿//<PropertyItems>
//      <PropertyItem>
//             <Ident>
//                      Стол обеденный
//             </Ident>
//             <Price>
//                      500
//             </Price>
//      </PropertyItem>
//      <PropertyItem>
//             <Ident>
//                       VAZ2105
//             </Ident>
//             <Price>
//                       1000
//             </Price>
//      </PropertyItem>
//</PropertyItems>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using DataContracts;

namespace XMLTransformer
{
    public class XmlTransformer : IXmlTransformer
    {
        public void Export(List<PropertyItem> items, string pathToXml)
        {
            var xDoc = new XDocument(new XElement("PropertyItems"));
            foreach (var item in items)
            {
                xDoc.Element("PropertyItems").Add(new XElement("PropertyItem", new XElement("Ident", item.Ident), new XElement("Price", item.Price)));
            }
            xDoc.Save(pathToXml);
        }
        
        public List<PropertyItem> Import(string filePath)
        {
            var propertyItems = new List<PropertyItem>();

            if (!File.Exists(filePath))
                throw new InvalidOperationException("Файл не найден");
            
            var xDoc = XDocument.Load(filePath);

            var xComponent = xDoc.Element("PropertyItems");

            if (xComponent != null)
            {
                propertyItems.AddRange(
                    xComponent.Elements("PropertyItem")
                        .Where(element => element != null)
                        .Select(element =>
                        {
                            var ident = element.Element("Ident").Value;
                            var price = element.Element("Price").Value;
                            
                            return
                                new PropertyItem{ Ident = ident, Price = Convert.ToInt32(price) };
                        }));
            }
            return propertyItems;
        }

    }
}
